<template>
  <div>
    <div>
      <h2 style="margin-top: 0;">专家列表</h2>
      <p class="description">管理各专业组的评审专家信息</p>
    </div>

    <!-- 筛选与操作栏 -->
    <div class="filter-bar"
         style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
      <el-input
          placeholder="搜索专家..."
          prefix-icon="el-icon-search"
          style="width: 300px;"
          v-model="searchKeyword"
          @input="handleSearch"
      ></el-input>

      <div class="action-buttons">
        <!-- 添加专家按钮 -->
        <el-button type="primary" icon="el-icon-plus" @click="showAddExpertDialog = true">添加专家</el-button>
        <el-button type="default" icon="el-icon-upload">批量导入</el-button>
        <!-- 批量删除按钮 - 选中记录时可用 -->
        <el-button
            type="danger"
            icon="el-icon-delete"
            @click="handleBatchDelete"
            :disabled="selectedExpertIds.length === 0"
        >
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 专家列表表格 -->
    <div class="card-container">
      <el-tabs v-model="activeSpecialty" type="card" style="margin-bottom: 15px;" @tab-click="handleTabChange">
        <el-tab-pane label="全部专业组" name="all"></el-tab-pane>
        <el-tab-pane label="油气勘探" name="exploration"></el-tab-pane>
        <el-tab-pane label="油气藏工程" name="reservoir"></el-tab-pane>
        <el-tab-pane label="钻采与地面工程" name="drilling"></el-tab-pane>
        <el-tab-pane label="信息工程" name="information"></el-tab-pane>
      </el-tabs>

      <el-table
          :data="experts"
          border
          style="width: 100%;"
          @selection-change="handleSelectionChange"
          v-loading="loading"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <!-- 序号列 -->
        <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center"
        >
          <template slot-scope="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="专家姓名" width="120"></el-table-column>
        <el-table-column prop="category" label="专家类别">
          <template slot-scope="scope">
            <el-tag :type="getCategoryTagType(scope.row.category)">
              {{ scope.row.category }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="specialty" label="所属专业组"></el-table-column>
        <el-table-column prop="contactInfo" label="联系方式"></el-table-column>
        <el-table-column prop="status" label="专家状态">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="reviewCount"
            label="评审次数"
            width="120"
            align="center"
        >
          <template slot-scope="scope">
            <i class="el-icon-check-circle" style="color: #409eff; margin-right: 4px;"></i>
            {{ scope.row.reviewCount || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                style="color: #ff4d4f;"
                @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 15px; text-align: right;"
      ></el-pagination>
    </div>

    <!-- 添加专家弹窗 -->
    <el-dialog
        title="添加评审专家"
        :visible.sync="showAddExpertDialog"
        width="500px"
        top="10%"
        :before-close="handleAddDialogClose"
    >
      <el-form
          ref="addExpertForm"
          :model="addExpertForm"
          :rules="addExpertRules"
          label-width="120px"
          style="margin-top: 20px;"
      >
        <el-form-item label="专家姓名" prop="name">
          <el-input
              v-model="addExpertForm.name"
              placeholder="请输入专家姓名"
              maxlength="50"
              show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="专家类别" prop="category">
          <el-select
              v-model="addExpertForm.category"
              placeholder="请选择专家类别"
              style="width: 100%;"
          >
            <el-option label="公司领导" value="公司领导"></el-option>
            <el-option label="公司副总及专家" value="公司副总及专家"></el-option>
            <el-option label="专业部门领导（专家）" value="专业部门领导（专家）"></el-option>
            <el-option label="科研单位" value="科研单位"></el-option>
            <el-option label="二级单位" value="二级单位"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所属专业组" prop="specialty">
          <el-select
              v-model="addExpertForm.specialty"
              multiple
              placeholder="请选择专业组（可多选）"
              style="width: 100%;"
          >
            <el-option label="油气勘探" value="油气勘探"></el-option>
            <el-option label="油气藏工程" value="油气藏工程"></el-option>
            <el-option label="钻采与地面工程" value="钻采与地面工程"></el-option>
            <el-option label="信息工程" value="信息工程"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="专家状态" prop="status">
          <el-select
              v-model="addExpertForm.status"
              placeholder="请选择专家状态"
              style="width: 100%;"
          >
            <el-option label="正常" value="1"></el-option>
            <el-option label="冻结（资质过期/违规）" value="2"></el-option>
            <el-option label="退休" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="联系方式" prop="contactInfo">
          <el-input
              v-model="addExpertForm.contactInfo"
              placeholder="请输入联系方式（电话/邮箱，多个用英文逗号分隔）"
              maxlength="200"
              show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleAddDialogClose">取消</el-button>
        <el-button type="primary" @click="handleAddExpert">确定添加</el-button>
      </div>
    </el-dialog>

  <!-- 编辑专家弹窗 -->
  <el-dialog
      title="编辑评审专家"
      :visible.sync="showEditExpertDialog"
      width="500px"
      top="10%"
      :before-close="handleEditDialogClose"
  >
    <el-form
        ref="editExpertForm"
        :model="editExpertForm"
        :rules="addExpertRules"
        label-width="120px"
        style="margin-top: 20px;"
    >
      <el-form-item prop="id" hidden>
        <el-input v-model="editExpertForm.id"></el-input>
      </el-form-item>

      <el-form-item label="专家姓名" prop="name">
        <el-input
            v-model="editExpertForm.name"
            placeholder="请输入专家姓名"
            maxlength="50"
            show-word-limit
        ></el-input>
      </el-form-item>

      <el-form-item label="专家类别" prop="category">
        <el-select
            v-model="editExpertForm.category"
            placeholder="请选择专家类别"
            style="width: 100%;"
        >
          <el-option label="公司领导" value="公司领导"></el-option>
          <el-option label="公司副总及专家" value="公司副总及专家"></el-option>
          <el-option label="专业部门领导（专家）" value="专业部门领导（专家）"></el-option>
          <el-option label="科研单位" value="科研单位"></el-option>
          <el-option label="二级单位" value="二级单位"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属专业组" prop="specialty">
        <el-select
            v-model="editExpertForm.specialty"
            multiple
            placeholder="请选择专业组（可多选）"
            style="width: 100%;"
        >
          <el-option label="油气勘探" value="油气勘探"></el-option>
          <el-option label="油气藏工程" value="油气藏工程"></el-option>
          <el-option label="钻采与地面工程" value="钻采与地面工程"></el-option>
          <el-option label="信息工程" value="信息工程"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="专家状态" prop="status">
        <el-select
            v-model="editExpertForm.status"
            placeholder="请选择专家状态"
            style="width: 100%;"
        >
          <el-option label="正常" value="1"></el-option>
          <el-option label="冻结（资质过期/违规）" value="2"></el-option>
          <el-option label="退休" value="3"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="联系方式" prop="contactInfo">
        <el-input
            v-model="editExpertForm.contactInfo"
            placeholder="请输入联系方式（电话/邮箱，多个用英文逗号分隔）"
            maxlength="200"
            show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleEditDialogClose">取消</el-button>
      <el-button type="primary" @click="handleUpdateExpert">确定更新</el-button>
    </div>
  </el-dialog>

  <!-- 确认删除弹窗 -->
  <el-dialog
      title="确认删除"
      :visible.sync="showDeleteConfirmDialog"
      width="300px"
      top="10%"
      :show-close="false"
  >
    <div style="text-align: center;">
      <i class="el-icon-warning" style="color: #faad14; font-size: 24px; margin-right: 10px;"></i>
      <span>{{ deleteConfirmText }}</span>
    </div>
    <div slot="footer" style="text-align: center;">
      <el-button @click="showDeleteConfirmDialog = false">取消</el-button>
      <el-button type="danger" @click="confirmDelete">删除</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
import {getExpertPage, addExpert, updateExpert, deleteExpert, getExpertById, deleteExpertBatch} from '@/api/expert'

export default {
  data() {
    return {
      // 基础状态
      activeSpecialty: 'all',
      searchKeyword: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,

      // 选中的专家ID列表（用于批量删除）
      selectedExpertIds: [],

      // 删除确认弹窗相关
      showDeleteConfirmDialog: false,
      deleteConfirmText: '',
      deleteType: '', // 'single' 单条删除, 'batch' 批量删除
      currentDeleteId: null, // 当前要删除的专家ID

      // 添加专家相关状态
      showAddExpertDialog: false,
      addExpertForm: {
        name: '',
        category: '',
        specialty: [],
        status: '1', // 默认为正常状态
        contactInfo: '',
        reviewCount: 0 // 默认为0，自动累加
      },
      addExpertRules: {
        name: [
          { required: true, message: '请输入专家姓名', trigger: 'blur' },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z\s]{1,50}$/,
            message: '姓名只能包含中文、英文和空格，长度1-50字',
            trigger: 'blur'
          }
        ],
        category: [
          { required: true, message: '请选择专家类别', trigger: 'change' }
        ],
        specialty: [
          { required: true, message: '请至少选择一个所属专业组', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择专家状态', trigger: 'change' }
        ]
      },

      // 编辑专家相关状态
      showEditExpertDialog: false,
      editExpertForm: {
        id: null,
        name: '',
        category: '',
        specialty: [],
        status: '1',
        contactInfo: '',
        reviewCount: 0
      },

      // 专家列表数据
      experts: []
    };
  },

  created() {
    // 组件创建时加载数据
    this.fetchExpertList();
  },

  methods: {
    // 获取专家列表数据
    async fetchExpertList() {
      this.loading = true;
      try {
        // 构建查询参数
        const specialtyMap = {
          exploration: '油气勘探',
          reservoir: '油气藏工程',
          drilling: '钻采与地面工程',
          information: '信息工程'
        };

        // 构建查询条件
        const filters = {};
        if (this.activeSpecialty !== 'all') {
          filters.specialty = specialtyMap[this.activeSpecialty];
        }
        if (this.searchKeyword) {
          filters.name = this.searchKeyword;
        }
        console.log(filters)
        // 调用接口
        const response = await getExpertPage({
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          filters: filters
        });

        // 假设接口返回格式为 { code: 200, data: { list: [], total: 0 } }
        if (response.code === '200') {
          this.experts = response.data.records || [];
          this.total = response.data.total || 0;
        } else {
          this.$message.error('获取专家列表失败：' + (response.msg || '未知错误'));
        }
      } catch (error) {
        console.error('获取专家列表异常:', error);
        this.$message.error('获取专家列表失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },

    // 标签类型映射
    getCategoryTagType(category) {
      const typeMap = {
        '公司领导': 'danger',
        '公司副总及专家': 'primary',
        '专业部门领导（专家）': 'success',
        '科研单位': 'info',
        '二级单位': 'warning'
      };
      return typeMap[category] || 'info';
    },

    // 状态文本转换（1-正常 2-冻结 3-退休）
    getStatusText(status) {
      const statusMap = {
        1: '正常',
        2: '冻结',
        3: '退休'
      };
      return statusMap[status] || '未知';
    },

    // 状态标签样式
    getStatusTagType(status) {
      const typeMap = {
        1: 'success',  // 正常-绿色
        2: 'warning',  // 冻结-黄色
        3: 'info'      // 退休-蓝色
      };
      return typeMap[status] || 'default';
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchExpertList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchExpertList();
    },
    handleTabChange() {
      this.currentPage = 1;
      this.searchKeyword = '';
      this.selectedExpertIds = []; // 切换标签页时清空选择
      this.fetchExpertList();
    },
    handleSearch() {
      this.currentPage = 1;
      this.selectedExpertIds = []; // 搜索时清空选择
      this.fetchExpertList();
    },

    // 处理选择变化（用于批量删除）
    handleSelectionChange(selection) {
      this.selectedExpertIds = selection.map(item => item.id);
    },

    // 添加专家相关方法
    handleAddDialogClose() {
      this.showAddExpertDialog = false;
      this.$nextTick(() => {
        this.$refs.addExpertForm?.resetFields();
        this.addExpertForm = {
          name: '',
          category: '',
          specialty: [],
          status: '1',
          contactInfo: '',
          reviewCount: 0
        };
      });
    },

    async handleAddExpert() {
      this.$refs.addExpertForm.validate(async (isValid) => {
        if (!isValid) return;

        const newExpert = {
          name: this.addExpertForm.name.trim(),
          category: this.addExpertForm.category,
          specialty: this.addExpertForm.specialty.join(','), // 用英文逗号分隔
          status: parseInt(this.addExpertForm.status),
          contactInfo: this.addExpertForm.contactInfo.trim() || null,
          reviewCount: 0 // 新增专家初始评审次数为0
        };

        try {
          this.loading = true;
          const response = await addExpert(newExpert);

          if (response.code === '200') {
            this.$message.success('专家添加成功！');
            this.handleAddDialogClose();
            this.activeSpecialty = 'all';
            await this.fetchExpertList(); // 重新加载列表
          } else {
            this.$message.error('专家添加失败：' + (response.msg || '未知错误'));
          }
        } catch (error) {
          console.error('添加专家异常:', error);
          this.$message.error('专家添加失败，请稍后重试');
        } finally {
          this.loading = false;
        }
      });
    },

    // 编辑专家相关方法
    async handleEdit(expert) {
      try {
        this.loading = true;
        const response = await getExpertById(expert.id);

        if (response.code === '200') {
          this.showEditExpertDialog = true;
          const expertData = response.data;
          this.$nextTick(() => {
            this.editExpertForm = {
              ...expertData,
              specialty: expertData.specialty ? expertData.specialty.split(',') : [],
              status: expertData.status.toString()
            };
          });
        } else {
          this.$message.error('获取专家详情失败：' + (response.msg || '未知错误'));
        }
      } catch (error) {
        console.error('获取专家详情异常:', error);
        this.$message.error('获取专家详情失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },

    handleEditDialogClose() {
      this.showEditExpertDialog = false;
      this.$nextTick(() => {
        this.$refs.editExpertForm?.resetFields();
      });
    },

    async handleUpdateExpert() {
      this.$refs.editExpertForm.validate(async (isValid) => {
        if (!isValid) return;

        const updatedExpert = {
          ...this.editExpertForm,
          specialty: this.editExpertForm.specialty.join(','),
          status: parseInt(this.editExpertForm.status)
        };

        try {
          this.loading = true;
          const response = await updateExpert(updatedExpert);

          if (response.code === '200') {
            this.$message.success('专家信息更新成功！');
            this.handleEditDialogClose();
            await this.fetchExpertList(); // 重新加载列表
          } else {
            this.$message.error('专家信息更新失败：' + (response.msg || '未知错误'));
          }
        } catch (error) {
          console.error('更新专家异常:', error);
          this.$message.error('专家信息更新失败，请稍后重试');
        } finally {
          this.loading = false;
        }
      });
    },

    // 删除相关方法
    // 单条删除
    handleDelete(expert) {
      this.deleteType = 'single';
      this.currentDeleteId = expert.id;
      this.deleteConfirmText = `确定要删除专家【${expert.name}】吗？`;
      this.showDeleteConfirmDialog = true;
    },

    // 批量删除
    handleBatchDelete() {
      this.deleteType = 'batch';
      this.deleteConfirmText = `确定要删除选中的${this.selectedExpertIds.length}位专家吗？`;
      this.showDeleteConfirmDialog = true;
    },

    // 确认删除
    async confirmDelete() {
      try {
        this.loading = true;

        if (this.deleteType === 'single') {
          // 单条删除
          const response = await deleteExpert(this.currentDeleteId);
          if (response.code === '200') {
            this.$message.success('专家删除成功！');
          } else {
            this.$message.error('专家删除失败：' + (response.msg || '未知错误'));
            return;
          }
        } else {
          // 批量删除 - 直接调用批量接口
          const response = await deleteExpertBatch(this.selectedExpertIds);
          if (response.code === '200') {
            this.$message.success(`成功删除${this.selectedExpertIds.length}位专家！`);
          } else {
            this.$message.error('批量删除失败：' + (response.msg || '未知错误'));
            return;
          }
        }

        // 清空选择
        this.selectedExpertIds = [];
        // 关闭弹窗
        this.showDeleteConfirmDialog = false;
        // 重新加载列表
        await this.fetchExpertList();
      } catch (error) {
        console.error('删除专家异常:', error);
        this.$message.error('删除失败，请稍后重试！');
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>
